package com.taokatao.cardmee.business.cardcrud;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Context;
import android.os.Build;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.DecelerateInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.taokatao.cardmee.App;
import com.taokatao.cardmee.C;
import com.taokatao.cardmee.R;
import com.taokatao.cardmee.common.widget.RecyclerItemDecoration;
import com.taokatao.cardmee.db.CardStoreDao;
import com.taokatao.cardmee.db.model.CardStore;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;


public class FastCompareLayout extends FrameLayout {

    private List<CardStore> cardStoreList;
    RecyclerView vRecycler;
    FastCompareAdapter adapter;

    final DecelerateInterpolator interpolator = new DecelerateInterpolator(2f);
    ValueAnimator animator;
    boolean animShow, animHide;

    public FastCompareLayout(Context context) {
        this(context, null);
    }

    public FastCompareLayout(Context context, AttributeSet attrs) {
        super(context, attrs);

        addView(vRecycler = new RecyclerView(context));

        int elevation = (int) (getResources().getDisplayMetrics().density + 0.5f) * 4;
        RelativeLayout.MarginLayoutParams lpRecycler = ((MarginLayoutParams) vRecycler.getLayoutParams());
        lpRecycler.setMargins(elevation * 2, elevation * 2, elevation * 2, elevation * 2);
        lpRecycler.width = RecyclerView.LayoutParams.MATCH_PARENT;
        ((LayoutParams) vRecycler.getLayoutParams()).gravity = Gravity.BOTTOM;

        vRecycler.setLayoutManager(new LinearLayoutManager(context));
        vRecycler.addItemDecoration(new RecyclerItemDecoration(context, LinearLayoutManager.VERTICAL));

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            vRecycler.setBackgroundColor(0xFFFFFFFF);
            vRecycler.setElevation(elevation);
        }

        vRecycler.setAdapter(adapter = new FastCompareAdapter());

        if (!isInEditMode()) {
            CardStoreDao cardStoreDao = App.i().getCommonDBSession().getCardStoreDao();
            cardStoreList = cardStoreDao.queryBuilder().where(CardStoreDao.Properties.SearchKeys.isNotNull(),
                    CardStoreDao.Properties.BusinessId.notEq(C.settings.BUSINESS_OTHER_ID)).orderAsc(CardStoreDao.Properties.Sort)
                    .orderDesc(CardStoreDao.Properties.UseCount)
                    .orderAsc(CardStoreDao.Properties.BusinessName).list();
        }
    }

    public void setCallback(final Callback cb) {
        if (adapter != null) {
            adapter.callback = new Callback() {
                @Override
                public void onCardStoreSelected(View vIcon, CardStore cs) {
                    postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            animHide();
                        }
                    }, 200);
                    cb.onCardStoreSelected(vIcon, cs);
                }
            };
        }
    }

    public void filter(String s) {
        if (TextUtils.isEmpty(s) || cardStoreList == null) {
            setVisibility(View.GONE);
            return;
        }

        String lowerSearch = s.replaceAll(" ", "").toLowerCase();
        List<CardStore> filterResult = new ArrayList<>();
        for (CardStore cs : cardStoreList) {

            if (filterResult.size() > 10) break;

            String lowerSearchKeys = cs.getSearchKeys().toLowerCase();
            if (lowerSearchKeys.contains(lowerSearch)) {
                filterResult.add(cs);
            }
        }

        if (filterResult.size() > 0) {
            animShow();
        } else {
            animHide();
        }

        adapter.set(filterResult);
    }

    public void animShow() {
        if (animShow || getVisibility() == View.VISIBLE) return;

        if (animator != null) animator.cancel();

        animator = ValueAnimator.ofFloat(0, 1);
        animator.setDuration(150);
        animator.setInterpolator(interpolator);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float) animation.getAnimatedValue();
                setTranslationY((int) (getHeight() * 0.1 * (1 - value)));
                setAlpha(value);
            }
        });
        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                setTranslationY(0);
                setAlpha(1);
                animShow = false;
            }

            @Override
            public void onAnimationCancel(Animator animation) {
                super.onAnimationCancel(animation);
                setTranslationY(0);
                setAlpha(1);
                animShow = false;
            }

            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                setVisibility(View.VISIBLE);
                animShow = true;
            }
        });

        animator.start();
    }

    public void animHide() {
        if (animHide || getVisibility() == View.GONE) return;

        if (animator != null) animator.cancel();

        animator = ValueAnimator.ofFloat(1, 0);
        animator.setDuration(150);
        animator.setInterpolator(interpolator);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float) animation.getAnimatedValue();
                setTranslationY((int) (getHeight() * 0.1 * (1 - value)));
                setAlpha(value);
            }
        });
        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                setTranslationY(0);
                setAlpha(0);
                setVisibility(View.GONE);
                animHide = false;
            }

            @Override
            public void onAnimationCancel(Animator animation) {
                super.onAnimationCancel(animation);
                setTranslationY(0);
                setAlpha(0);
                setVisibility(View.GONE);
                animHide = false;
            }

            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                animHide = true;
            }
        });
        animator.start();
    }

    interface Callback {
        void onCardStoreSelected(View iIcon, CardStore cs);
    }

    static class FastCompareAdapter extends RecyclerView.Adapter {
        Callback callback;
        List<CardStore> dataList;

        public void set(List<CardStore> cardStoreList) {
            if (cardStoreList != null) {
                dataList = cardStoreList;
                notifyDataSetChanged();
            }
        }

        class ViewHolder extends RecyclerView.ViewHolder implements OnClickListener {
            CardStore cs;
            @BindView(R.id.i_icon) ImageView iIcon;
            @BindView(R.id.t_name) TextView tName;

            ViewHolder(View view) {
                super(view);
                ButterKnife.bind(this, view);
                itemView.setOnClickListener(this);
            }

            @Override
            public void onClick(View v) {
                if (callback != null) {
                    callback.onCardStoreSelected(iIcon, cs);
                }
            }
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_card_search_content, parent, false));
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            ViewHolder vh = (ViewHolder) holder;
            vh.cs = dataList.get(position);
            Glide.with(vh.iIcon.getContext()).load(vh.cs.getBusinessIcon()).into(vh.iIcon);
            vh.tName.setText(vh.cs.getBusinessName());
        }

        @Override
        public int getItemCount() {
            return dataList != null ? dataList.size() : 0;
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (animator != null) animator.cancel();
    }
}
